// 通用Table表格列表实现 搜索 分页 删除 修改状态等
// 在文件顶部添加类型导入
import type { Ref } from 'vue'
import { reactive, ref } from 'vue'
import { showMessage } from '@/utils/elementTools'

// 定义Options接口
interface TableOptions {
  getList: (page: number, query?: any) => Promise<any>
  query?: Record<string, any>
  onGetListSuccess?: (res: any) => void
  updateStatus?: (id: number, status: number) => Promise<any>
  delete: (id: number | number[]) => Promise<any>
  updateManyStatus?: (ids: number[], status: number) => Promise<any>
}

type QueryType = {
  keyword?: string
  title?: string
  tab?: string
  category_id?: number | null
  limit?: number
}

// 设置useInitTable函数的返回数据类型
type UseInitTableReturn = {
  query: QueryType
  searchFormRef: Ref<null>
  handleReset: (() => void) | null
  tableRef: Ref<{ clearSelection: () => void } | null>
  tableData: Ref<any[]>
  loading: Ref<boolean>
  currentPage: Ref<number>
  pageSize: Ref<number>
  total: Ref<number>
  getData: (p?: number | null) => void
  handleStatusChange: (row: any, status: number) => void
  handleDelete: (id: number) => void
  handleDeleteAll: () => void
  handleUpdateManyStatus: (status: number) => void
  handleSelectionChange: (rows: any) => void
}

// 修改函数签名，指定返回类型
export function useInitTable(opt: TableOptions): UseInitTableReturn {
  // opt.getList 必传 获取列表数据方法
  // opt.query 可选 搜索表单数据
  // opt.onGetListSuccess 可选 获取列表数据成功回调方法 用于处理特殊要求的数据
  if (!opt.getList) {
    showMessage('请传入getList方法', 'error')
    return null as any
  }

  // 搜索表单
  const searchFormRef = ref(null)
  let query = reactive({} as QueryType)

  let handleReset = null
  if (opt.query) {
    query = reactive({ ...opt.query })
    handleReset = () => {
      Object.keys(query).forEach((key) => {
        const validKey = key as keyof QueryType
        if (validKey in query) {
          query[validKey] = opt.query![validKey]
        }
      })
      getData()
    }
  }

  // Table表格数据分页
  const tableData = ref([])
  const loading = ref(false)
  const currentPage = ref(1)
  const pageSize = ref(opt.query?.limit || 10)
  const total = ref(0)

  // 获取数据
  function getData(p = null) {
    if (typeof p === 'number') {
      currentPage.value = p
    }
    loading.value = true
    opt
      .getList(currentPage.value, query)
      .then((res: any) => {
        if (opt.onGetListSuccess && typeof opt.onGetListSuccess === 'function') {
          opt.onGetListSuccess(res)
        } else {
          tableData.value = res.data.list
        }
        total.value = res.data.totalCount
      })
      .finally(() => {
        loading.value = false
      })
  }

  const handleStatusChange = (row: any, status: number) => {
    row.statusLoading = true
    opt.updateStatus!(row.id, status)
      .then((res) => {
        showMessage('状态修改成功')
        row.status = status // 更新表格数据
        getData()
      })
      .finally(() => {
        row.statusLoading = false
      })
  }
  // 单条删除
  const handleDelete = (id: number) => {
    opt.delete(id).then((res) => {
      showMessage('删除成功')
      getData()
    })
  }
  // 选择多条批量删除
  let ids = ref<number[]>([])
  // 修改tableRef类型
  const tableRef: Ref<{ clearSelection: () => void } | null> = ref(null)

  const handleDeleteAll = () => {
    loading.value = true
    opt
      .delete(ids.value)
      .then(() => {
        showMessage('删除成功')
        if (tableRef.value) {
          tableRef.value!.clearSelection()
        }
        getData()
      })
      .finally(() => {
        loading.value = false
      })
  }

  const handleUpdateManyStatus = (status: number) => {
    loading.value = true
    opt.updateManyStatus!(ids.value, status)
      .then(() => {
        showMessage(status ? '上架成功' : '下架成功')
        if (tableRef.value) {
          tableRef.value!.clearSelection()
        }
        getData()
      })
      .finally(() => {
        loading.value = false
      })
  }

  const handleSelectionChange = (rows: any) => {
    ids.value = rows.map((row: any) => row.id)
  }

  onMounted(() => {
    getData()
  })

  return {
    // @ts-ignore
    getData,
    query,
    searchFormRef,
    handleReset,
    tableRef,
    tableData,
    loading,
    currentPage,
    pageSize,
    total,
    handleStatusChange,
    handleDelete,
    handleDeleteAll,
    handleUpdateManyStatus,
    handleSelectionChange
  }
}

// 定义FormOptions接口
interface FormOptions {
  initialForm?: Record<string, any>
  rules?: Record<string, any>
  onBeforeSubmit?: (form: any) => any
  update?: (id: number, body: any) => Promise<any>
  create?: (body: any) => Promise<any>
  getData?: (page: number) => void
}

// 封装 新增 修改
type DrawerComponent = { showLoading: () => void; hideDrawer: () => void; hideLoading: () => void; showDrawer: () => void }

export function useInitForm(opt: FormOptions = {}) {
  const formDrawerRef: Ref<DrawerComponent | null> = ref(null)
  type FormComponent = { validate: (callback: (valid: boolean) => void) => void }
  const formRef: Ref<FormComponent | null> = ref(null)
  // const formRef = ref(null)
  const editId = ref(0)
  const drawerTitle = computed(() => (editId.value == 0 ? '新增' : '编辑'))

  // 表单数据
  const initialForm = opt.initialForm || {}

  const form = reactive({ ...initialForm })
  const rules = opt.rules || {}
  // 为了修复类型错误，需要明确指定 formDrawerRef 的类型

  const handleSubmit = (currentPage: number = 1) => {
    formRef.value?.validate((valid: boolean) => {
      if (!valid) return
      formDrawerRef.value?.showLoading()

      // onBeforeSubmit 处理特殊数据
      let body = {}
      if (opt.onBeforeSubmit && typeof opt.onBeforeSubmit === 'function') {
        body = opt.onBeforeSubmit({ ...form })
      } else {
        body = form
      }

      const fun = editId.value ? opt.update!(editId.value, body) : opt.create!(body)
      fun
        .then((res) => {
          showMessage(drawerTitle.value + '成功', 'success')
          opt.getData!(editId.value ? currentPage : 1)
          formDrawerRef.value?.hideDrawer()
        })
        .finally(() => {
          formDrawerRef.value?.hideLoading()
        })
    })
  }
  const handleAdd = () => {
    Object.assign(form, initialForm)
    editId.value = 0
    formDrawerRef.value?.showDrawer()
  }

  const handleEdit = (item: any) => {
    Object.assign(form, item)
    editId.value = item.id
    formDrawerRef.value?.showDrawer()
  }
  return {
    formDrawerRef,
    formRef,
    drawerTitle,
    form,
    rules,
    handleSubmit,
    handleAdd,
    handleEdit
  }
}
